<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件上传中心</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
        }

        body {
            min-height: 100vh;
            background-color: #f4f7fa;
            color: #333;
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .container {
            width: 100%;
            max-width: 600px;
            background-color: #fff;
            border-radius: 12px;
            box-shadow: 0 8px 30px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        .header {
            background: linear-gradient(135deg, #5B86E5, #36D1DC);
            color: white;
            padding: 25px 30px;
            text-align: center;
        }

        .header h1 {
            font-size: 24px;
            font-weight: 600;
        }

        .content {
            padding: 30px;
        }

        /* 上传区域样式 */
        .upload-area {
            border: 2px dashed #c0c4cc;
            border-radius: 8px;
            padding: 40px 20px;
            text-align: center;
            cursor: pointer;
            transition: all 0.3s ease;
            margin-bottom: 30px;
        }

        .upload-area:hover {
            border-color: #5B86E5;
            background-color: #f0f5ff;
        }

        .upload-area.active {
            border-color: #36D1DC;
            background-color: #e8fff3;
        }

        .upload-icon {
            font-size: 40px;
            color: #5B86E5;
            margin-bottom: 15px;
        }

        .upload-text h3 {
            font-size: 18px;
            margin-bottom: 8px;
            color: #333;
        }

        .upload-text p {
            font-size: 14px;
            color: #666;
        }

        #file-input {
            display: none;
        }

        /* 文件列表样式 */
        .file-list-title {
            font-size: 16px;
            font-weight: 600;
            margin-bottom: 15px;
            color: #666;
            display: none; /* Initially hidden */
        }

        .file-list {
            max-height: 200px;
            overflow-y: auto;
            margin-bottom: 30px;
        }

        .file-item {
            display: flex;
            align-items: center;
            padding: 12px 15px;
            background-color: #f9f9f9;
            border-radius: 6px;
            margin-bottom: 10px;
            animation: fadeIn 0.3s ease;
        }

        @keyframes fadeIn {
            from { opacity: 0; transform: translateY(10px); }
            to { opacity: 1; transform: translateY(0); }
        }

        .file-icon {
            font-size: 20px;
            color: #5B86E5;
            margin-right: 15px;
            flex-shrink: 0;
        }

        .file-info {
            flex-grow: 1;
            min-width: 0;
        }

        .file-name {
            font-weight: 500;
            margin-bottom: 4px;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .file-size {
            font-size: 12px;
            color: #999;
        }

        .file-remove {
            color: #ff6b6b;
            background: none;
            border: none;
            cursor: pointer;
            font-size: 18px;
            transition: color 0.2s;
            padding: 5px;
        }

        .file-remove:hover {
            color: #ff4949;
        }

        /* 上传按钮 */
        .upload-btn {
            width: 100%;
            padding: 14px;
            background-color: #5B86E5;
            color: white;
            border: none;
            border-radius: 8px;
            font-size: 16px;
            font-weight: 600;
            cursor: pointer;
            transition: background-color 0.3s ease;
            opacity: 0.7;
            pointer-events: none;
        }

        .upload-btn.enabled {
            opacity: 1;
            pointer-events: auto;
        }

        .upload-btn:hover {
            background-color: #4a74d1;
        }

        /* 上传状态提示 */
        .status-message {
            text-align: center;
            padding: 15px;
            font-size: 14px;
            display: none; /* Initially hidden */
        }
        .status-message.success {
            color: #28a745;
            display: block;
        }
        .status-message.error {
            color: #dc3545;
            display: block;
        }

    </style>
    <!-- 引入 Font Awesome 图标库 -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
</head>
<body>

<div class="container">
    <div class="header">
        <h1>文件上传中心</h1>
    </div>
    <div class="content">
        <form id="upload-form" action="UploadServlet" method="post" enctype="multipart/form-data">
            <div class="upload-area" id="upload-area">
                <input type="file" id="file-input" name="file" multiple />
                <div class="upload-icon">
                    <i class="fas fa-cloud-upload-alt"></i>
                </div>
                <div class="upload-text">
                    <h3>拖拽文件到此处或点击上传</h3>
                    <p>支持多文件上传</p>
                </div>
            </div>

            <h3 class="file-list-title" id="file-list-title">已选择文件</h3>
            <div class="file-list" id="file-list">
                <!-- 选中的文件将动态添加到这里 -->
            </div>

            <button type="submit" class="upload-btn" id="upload-btn">开始上传</button>
        </form>
        <div id="status-message" class="status-message"></div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function() {
        const fileInput = document.getElementById('file-input');
        const uploadArea = document.getElementById('upload-area');
        const fileList = document.getElementById('file-list');
        const fileListTitle = document.getElementById('file-list-title');
        const uploadBtn = document.getElementById('upload-btn');
        const uploadForm = document.getElementById('upload-form');
        const statusMessage = document.getElementById('status-message');

        let selectedFiles = [];

        // 点击上传区域触发文件选择
        uploadArea.addEventListener('click', () => {
            fileInput.click();
        });

        // 拖拽功能
        uploadArea.addEventListener('dragover', (e) => {
            e.preventDefault();
            uploadArea.classList.add('active');
        });

        uploadArea.addEventListener('dragleave', () => {
            uploadArea.classList.remove('active');
        });

        uploadArea.addEventListener('drop', (e) => {
            e.preventDefault();
            uploadArea.classList.remove('active');
            if (e.dataTransfer.files.length) {
                fileInput.files = e.dataTransfer.files;
                handleFilesSelection();
            }
        });

        // 选择文件后处理
        fileInput.addEventListener('change', handleFilesSelection);

        function handleFilesSelection() {
            if (fileInput.files.length === 0) return;

            // 清空现有列表（如果是重新选择）
            if (selectedFiles.length === 0) {
                fileList.innerHTML = '';
            }

            // 向 selectedFiles 数组添加新文件
            for (let i = 0; i < fileInput.files.length; i++) {
                const file = fileInput.files[i];
                // 简单去重
                if (!selectedFiles.some(f => f.name === file.name && f.size === file.size)) {
                    selectedFiles.push(file);
                    addFileToDOM(file);
                }
            }

            updateUI();
        }

        // 将文件添加到页面
        function addFileToDOM(file) {
            const fileItem = document.createElement('div');
            fileItem.className = 'file-item';
            fileItem.dataset.index = selectedFiles.length - 1; // 使用索引作为标识

            const fileSize = formatFileSize(file.size);

            fileItem.innerHTML = `
                    <div class="file-icon">
                        <i class="fas fa-file"></i>
                    </div>
                    <div class="file-info">
                        <div class="file-name">${file.name}</div>
                        <div class="file-size">${fileSize}</div>
                    </div>
                    <button class="file-remove" title="移除文件">
                        <i class="fas fa-times"></i>
                    </button>
                `;

            fileList.appendChild(fileItem);

            // 为删除按钮添加事件
            fileItem.querySelector('.file-remove').addEventListener('click', (e) => {
                const index = parseInt(e.currentTarget.closest('.file-item').dataset.index);
                removeFile(index);
            });
        }

        // 移除文件
        function removeFile(index) {
            // 从数组中移除
            selectedFiles.splice(index, 1);

            // 从DOM中移除
            const fileItems = document.querySelectorAll('.file-item');
            if (fileItems[index]) {
                fileItems[index].classList.add('fadeOut'); // 添加淡出动画
                setTimeout(() => {
                    fileItems[index].remove();
                    // 重新索引
                    document.querySelectorAll('.file-item').forEach((item, newIndex) => {
                        item.dataset.index = newIndex;
                    });
                    updateUI();
                }, 300); // 等待动画结束
            } else {
                updateUI(); // 如果元素已不存在，直接更新UI
            }
        }

        // 更新界面状态
        function updateUI() {
            if (selectedFiles.length > 0) {
                fileListTitle.style.display = 'block';
                uploadBtn.classList.add('enabled');
            } else {
                fileListTitle.style.display = 'none';
                uploadBtn.classList.remove('enabled');
                // 重置文件输入，否则再次选择相同文件不会触发change事件
                fileInput.value = '';
            }
        }

        // 文件大小格式化
        function formatFileSize(bytes) {
            if (bytes === 0) return '0 Bytes';
            const k = 1024;
            const sizes = ['Bytes', 'KB', 'MB', 'GB'];
            const i = Math.floor(Math.log(bytes) / Math.log(k));
            return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
        }

        // 表单提交处理
        uploadForm.addEventListener('submit', function(e) {
            e.preventDefault(); // 阻止默认提交

            if (selectedFiles.length === 0) {
                showStatus('请先选择文件', 'error');
                return;
            }

            uploadBtn.disabled = true;
            uploadBtn.textContent = '正在上传...';

            const formData = new FormData(this);

            // 注意：这里我们重新构建FormData，以确保只包含selectedFiles中的文件
            // 因为原始的fileInput.files可能包含已被删除的文件
            formData.delete('file'); // 删除原有的file字段
            selectedFiles.forEach(file => {
                formData.append('file', file);
            });

            fetch(this.action, {
                method: 'POST',
                body: formData
            })
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.text();
                })
                .then(data => {
                    // 上传成功后重置
                    selectedFiles = [];
                    fileList.innerHTML = '';
                    updateUI();

                    // 显示成功消息
                    showStatus(data, 'success');

                    // 2秒后隐藏成功消息
                    // setTimeout(() => {
                    //     statusMessage.style.display = 'none';
                    // }, 3000);

                    console.log('Upload successful:', data);
                })
                .catch(error => {
                    console.error('Upload error:', error);
                    showStatus('文件上传失败，请重试。', 'error');
                })
                .finally(() => {
                    uploadBtn.disabled = false;
                    uploadBtn.textContent = '开始上传';
                });
        });

        // 显示状态消息
        function showStatus(message, type) {
            statusMessage.textContent = message;
            statusMessage.className = 'status-message ' + type;
            statusMessage.style.display = 'block';
        }
    });
</script>
</body>
</html>